<template>
  <div class="ad-campaigns-list">
    <!-- 过滤卡片 -->
    <el-card class="filter-card shadow-sm">
      <el-form :inline="true" :model="filterForm" class="demo-form-inline">
        <el-form-item label="计划名称">
          <el-input
              v-model="filterForm.campaignName"
              placeholder="请输入计划名称"
              clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="公司名称">
          <el-input
              v-model="filterForm.companyName"
              placeholder="请输入公司名称"
              clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
              v-model="filterForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
          >
            <el-option label="全部" value=""></el-option>
            <el-option label="草稿" :value="1"></el-option>
            <el-option label="审核中" :value="2"></el-option>
            <el-option label="运行中" :value="3"></el-option>
            <el-option label="暂停" :value="4"></el-option>
            <el-option label="结束" :value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchCampaigns" :loading="loading">
            <i class="el-icon-search"></i> 查询
          </el-button>
          <el-button @click="resetFilter">
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 广告计划列表 -->
    <el-card class="shadow-sm">
      <div slot="header" class="clearfix">
        <span>广告计划列表</span>
        <el-button
            style="float: right; margin-top: -5px"
            type="primary"
            @click="handleAdd"
        >
          新增
        </el-button>
      </div>

      <el-table
          :data="adList"
          border style="width: 100%">
        <el-table-column prop="campaignId" label="编号" width="70"></el-table-column>
        <el-table-column prop="campaignName" label="计划名称"></el-table-column>
        <el-table-column prop="companyName" label="公司名称"></el-table-column>
        <el-table-column prop="startTime" label="开始时间">
          <template #default="{ row }">
            {{ formatDate(row.startTime) }}
          </template>
        </el-table-column>
<!--        <el-table-column prop="endTime" label="结束时间">-->
<!--          <template #default="{ row }">-->
<!--            {{ formatDate(row.endTime) }}-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column prop="budget" label="预算" align="left">
          <template #default="{ row }">
            ¥ {{ row.budget }}
          </template>
        </el-table-column>
<!--        <el-table-column prop="dailyBudget" label="每日预算"  align="left">-->
<!--          <template #default="{ row }">-->
<!--            ¥ {{ row.dailyBudget }}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column prop="bidPrice" label="出价"  align="left">-->
<!--          <template #default="{ row }">-->
<!--            ¥ {{ row.bidPrice }}-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column prop="targetAudience" label="目标受众" min-width="120">
          <template #default="{ row }">
            <div class="audience-info">
              <div v-if="row.targetAudience.gender && row.targetAudience.gender.length">
                <span class="label">性别：</span>
                {{ formatGender(row.targetAudience.gender) }}
              </div>
              <div v-if="row.targetAudience.age_range && row.targetAudience.age_range.length">
                <span class="label">年龄：</span>
                {{ row.targetAudience.age_range.join(' - ') }}
              </div>
              <div v-if="row.targetAudience.interests && row.targetAudience.interests.length">
                <span class="label">兴趣：</span>
                {{ row.targetAudience.interests.join('、') }}
              </div>
            </div>

          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <!-- 1. 安全校验，确保 row 存在 -->
            <template v-if="row">
              <!-- 下拉操作 -->
              <el-dropdown
                  @command="(newStatus) => handleStatusChange(row, newStatus)"
                  :disabled="row.status === 5"
              >
        <span
            class="el-dropdown-link"
            :style="{ cursor: row.status === 5 ? 'default' : 'pointer' }"
        >
          <!-- 2. 状态标签 + 加载态 -->
          <el-tag
              :type="getStatusTagType(row.status)"
              style="display: inline-flex; align-items: center;"
          >
            <!-- 加载中 -->
            <i
                class="el-icon-loading"
                v-if="row.statusLoading"
                style="margin-right: 4px;"
            ></i>
            <!-- 正常状态文本 -->
            <template v-else>
              {{ getStatusText(row.status) }}
              <!-- 下拉箭头（非结束状态显示） -->
              <i
                  class="el-icon-arrow-down el-icon--right"
                  v-if="row.status !== 5"
                  style="margin-left: 4px;"
              ></i>
            </template>
          </el-tag>
        </span>

                <!-- 3. 下拉选项 -->
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                        v-for="option in getStatusOptions(row.status)"
                        :key="option.value"
                        :command="option.value"
                    >
                      {{ option.label }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="{ row }">
            <el-link type="primary" @click="handleView(row)">查看</el-link>
            <el-divider direction="vertical" />
            <el-link type="danger" @click="handleDelete(row)">删除</el-link>
            <el-divider direction="vertical" />
            <el-link type="success" @click="handleEdit(row)">编辑</el-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 20px; text-align: right;"
      ></el-pagination>
    </el-card>

    <!-- 新增/编辑/查看弹窗 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="60%"
        :close-on-click-modal="false"
        :before-close="handleClose"
    >
      <el-form
          :model="form"
          label-width="120px"
          ref="formRef"
      >
        <el-form-item
            label="计划名称"
            :rules="{ required: true, message: '请输入计划名称', trigger: 'blur' }"
        >
          <el-input
              v-model="form.campaignName"
              placeholder="请输入计划名称"
              :disabled="isViewMode"
          ></el-input>
        </el-form-item>


        <el-form-item
            label="广告公司"
            :rules="{ required: true, message: '请选择广告公司', trigger: 'change' }"
        >
          <el-select v-model="form.advertiserId" placeholder="请选择广告公司" :disabled="isViewMode">
            <el-option
                v-for="item in advertiserOptions"
                :key="item.advertiser_id"
                :label="item.company_name"
                :value="item.advertiser_id"
            />
          </el-select>
        </el-form-item>


        <el-form-item
            label="预算"
            :rules="[
            { required: true, message: '请输入预算', trigger: 'blur' },
            { type: 'number', message: '请输入数字', trigger: 'blur' }
          ]"
        >
          <el-input
              v-model.number="form.budget"
              placeholder="请输入预算"
              :disabled="isViewMode"
          ></el-input>
        </el-form-item>

        <el-form-item
            label="每日预算"
            :rules="[
            { type: 'number', message: '请输入数字', trigger: 'blur' }
          ]"
        >
          <el-input
              v-model.number="form.dailyBudget"
              placeholder="请输入每日预算"
              :disabled="isViewMode"
          ></el-input>
        </el-form-item>

        <el-form-item
            label="出价类型"
            :rules="{ required: true, message: '请选择出价类型', trigger: 'change' }"
        >
          <el-select
              v-model.number="form.biddingType"
              :disabled="isViewMode"
              placeholder="请选择出价类型"
              clearable
              style="width: 150px"
          >
            <el-option label="CPC" :value="1"></el-option>
            <el-option label="CPM" :value="2"></el-option>
            <el-option label="CPA" :value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
            label="出价"
            :rules="[
            { required: true, message: '请输入出价', trigger: 'blur' },
            { type: 'number', message: '请输入数字', trigger: 'blur' }
          ]"
        >
          <el-input
              v-model.number="form.bidPrice"
              placeholder="请输入出价"
              :disabled="isViewMode"
          ></el-input>
        </el-form-item>

        <el-form-item
            label="开始时间"
            :rules="{ required: true, message: '请选择开始时间', trigger: 'change' }"
        >
          <el-date-picker
              v-model="form.startTime"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
              :disabled="isViewMode"
          />
        </el-form-item>

        <el-form-item
            label="结束时间"
            :rules="{ required: true, message: '请选择结束时间', trigger: 'change' }"
        >
          <el-date-picker
              v-model="form.endTime"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
              :disabled="isViewMode"
          />
        </el-form-item>

        <el-form-item
            label="状态"
            v-if="!isViewMode"
            :rules="{ required: true, message: '请选择状态', trigger: 'change' }"
        >
          <el-select
              v-model.number="form.status"
              placeholder="请选择状态"
              clearable
              style="width: 100%"
              :disabled="isChange"
          >
            <el-option label="草稿" :value="1"></el-option>
            <el-option label="审核" :value="2"></el-option>
            <el-option label="运行" :value="3"></el-option>
            <el-option label="暂停" :value="4"></el-option>
            <el-option label="结束" :value="5"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="目标受众" min-width="140" :disabled="isViewMode">

          <div class="audience-info">
            <el-form-item label="性别">
              <el-checkbox-group v-model="form.targetAudience.gender">
                <el-checkbox value="1">男性</el-checkbox>
                <el-checkbox value="2">女性</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="年龄范围">
              <el-input-number
                  v-model.number="form.targetAudience.age_range[0]"
                  :min="1"
                  :max="100"
                  placeholder="最小年龄"
                  @change="validateAgeRange"
              ></el-input-number>
              <span class="age-range-separator">-</span>
              <el-input-number
                  v-model.number="form.targetAudience.age_range[1]"
                  :min="1"
                  :max="100"
                  placeholder="最大年龄"
                  @change="validateAgeRange"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="兴趣标签">
              <el-select
                  v-model="form.targetAudience.interests"
                  multiple
                  placeholder="请选择兴趣"
                  collapse-tags
                  :disabled="disabled"
              >
                <el-option
                    v-for="(interest, idx) in interestOptions"
                    :key="idx"
                    :label="interest"
                    :value="interest"
                />
              </el-select>
            </el-form-item>

          </div>
        </el-form-item>

        <el-form-item label="创建时间" v-if="isViewMode">
          <el-input
              v-model="form.createTime"
              :disabled="true"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ isViewMode ? '关闭' : '取消' }}</el-button>
          <el-button
              type="primary"
              @click="handleSave"
              v-if="!isViewMode"
              :loading="saveLoading"
          >确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from '@/utils/request';

export default {
  name: 'AdCampaignsList',

  data() {
    return {
      filterForm: {
        campaignName: '',
        companyName:'',
        status: ''
      },
      isChange:false, //控制编辑中的状态
      interestOptions: ['AI', '科技', '游戏', '阅读', '教育', '健康', '旅游', '美食'],
      isViewMode: false,
      loading: false,
      saveLoading: false,
      adList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      // 表单数据（新增/编辑/查看用）
      form: {
        advertisersStatus:'', //广告主状态
        biddingType: 1,
        campaignId: '',
        advertiserId:'',
        campaignName: '',
        startTime: '',
        endTime: '',
        budget: '',
        dailyBudget: '',
        bidPrice: '',
        targetAudience: {
          gender: [],
          age_range: [],
          interests: []
        },
        status: 1,
        createTime: '',
        updateTime: ''
      },
      // 状态映射
      statusMap: {
        1: '草稿',
        2: '审核中',
        3: '运行中',
        4: '暂停',
        5: '结束'
      },
      // 性别映射
      genderMap: {
        1: '男性',
        2: '女性'
      },
      // 出价类型映射
      biddingTypeMap: {
        1: 'CPC',
        2: 'CPM',
        3: 'CPA'
      },
      // 状态标签样式映射
      statusTagTypeMap: {
        1: 'info',
        2: 'warning',
        3: 'success',
        4: 'danger',
        5: 'primary'
      },
      // 状态流转规则
      statusFlowMap: {
        1: [ // 草稿状态可切换为
          { value: 2, label: '审核中' }
        ],
        2: [ // 审核中状态可切换为
          { value: 3, label: '运行中' },
          { value: 1, label: '草稿' }
        ],
        3: [ // 运行中状态可切换为
          { value: 4, label: '暂停' },
          { value: 5, label: '结束' }
        ],
        4: [ // 暂停状态可切换为
          { value: 3, label: '运行中' },
          { value: 5, label: '结束' }
        ],
        5: [] // 结束状态不可切换
      },
      //广告公司
      advertiserOptions:[]
    };
  },
  computed: {
    // 计算开始时间是否晚于结束时间
    isStartTimeLater() {
      if (!this.form.startTime || !this.form.endTime) return false;
      return new Date(this.form.startTime) > new Date(this.form.endTime);
    }
  },
  mounted() {
    this.getAdList();
    this.loadAdvertisers();
  },
  methods: {
    // 验证时间范围
    validateTimeRange() {
      if (this.isStartTimeLater) {
        this.$message.warning('开始时间不能晚于结束时间');
      }
    },

    //获取广告公司
    loadAdvertisers() {
      try {
        axios.get('/ad/dropdown').then(response =>{
          if (response.data.code === 200) {
            this.advertiserOptions = response.data.data;
          } else {
            this.$message.error('获取广告公司列表失败');
          }
        })
      } catch (error) {
        this.$message.error('网络异常，获取广告公司列表失败');
      }
    },

    // 格式化性别
    formatGender(genders) {
      if (!Array.isArray(genders) || genders.length === 0) return '全部';
      return genders.map(g => this.genderMap[g] || '未知').join('、');
    },

    // 获取状态文本
    getStatusText(status) {
      return this.statusMap[status] || '未知';
    },

    // 获取状态标签类型
    getStatusTagType(status) {
      return this.statusTagTypeMap[status] || 'info';
    },

    // 获取广告计划列表
    async getAdList() {
      this.loading = true;
      try {
        const response = await axios.get('/adCampaigns/page', {
          params: {
            campaignName: this.filterForm.campaignName,
            status: this.filterForm.status,
            companyName:this.filterForm.companyName,
            current: this.currentPage,
            size: this.pageSize
          }
        });

        if (response.data.code === 200) {
          this.adList = response.data.data.records.map(item => {
            // 处理 targetAudience 为 JSON 对象，方便后续展示
            item.targetAudience = typeof item.targetAudience === 'string'
                ? JSON.parse(item.targetAudience)
                : item.targetAudience;
            return item;
          });
          this.total = response.data.data.total;
        } else {
          this.$message.error(response.data.message || '获取列表失败');
        }
      } catch (error) {
        this.$message.error('网络异常，获取列表失败');
      } finally {
        this.loading = false;
      }
    },

    // 搜索
    searchCampaigns() {
      this.currentPage = 1;
      this.getAdList();
    },

    // 重置过滤条件
    resetFilter() {
      this.filterForm = {
        campaignName: '',
        status: ''
      };
      this.currentPage = 1;
      this.getAdList();
    },

    // 处理分页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.getAdList();
    },

    // 处理当前页变化
    handleCurrentChange(page) {
      this.currentPage = page;
      this.getAdList();
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },

    // 新增
    handleAdd() {
      this.dialogTitle = '新增广告计划';
      this.dialogVisible = true;
      this.isViewMode = false;
      this.form = {
        biddingType: 1,
        campaignId: '',
        campaignName: '',
        startTime: '',
        endTime: '',
        budget: '',
        dailyBudget: '',
        bidPrice: '',
        targetAudience: {
          gender: [],
          age_range: [],
          interests: []
        },
        status: 1,
        createTime: '',
        updateTime: ''
      };
    },
    // 年龄
    validateAgeRange() {
      const [min, max] = this.innerAgeRange;
      if (min && max && min > max) {
        this.$message.warning('最小年龄不能大于最大年龄');
        this.innerAgeRange[0] = max;
      }
    },

    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑广告计划';
      this.dialogVisible = true;
      this.isViewMode = false;
      // 深拷贝并处理 targetAudience 格式
      const formData = JSON.parse(JSON.stringify(row));
      formData.targetAudience = formData.targetAudience
          ? (typeof formData.targetAudience === 'string'
              ? JSON.parse(formData.targetAudience)
              : formData.targetAudience)
          : { gender: [], age_range: [], interests: [] };
      this.form = formData;

      if(this.form.advertisersStatus == 0){
        this.isChange = true;
      }else {
        this.isChange = false;
      }
    },

    // 查看
    handleView(row) {
      this.dialogTitle = '查看广告计划';
      this.dialogVisible = true;
      this.isViewMode = true;
      this.form = JSON.parse(JSON.stringify(row));
    },

    // 处理删除
    handleDelete(row) {
      if (row.status === 3) {
        this.$message.warning('运行中的广告计划不能删除');
        return;
      }

      this.$confirm('此操作将永久删除该记录，同时删除关联的广告创意, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await axios.delete('/adCampaigns/delete', {
            params: {
              campaignId: row.campaignId
            }
          });

          this.$message({
            type: 'success',
            message: '删除成功!'
          });

          this.getAdList();
        } catch (error) {
          this.$message.error('删除失败，请重试');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 关闭弹窗前的处理
    handleClose() {
      this.dialogVisible = false;
    },

    // 保存（新增/编辑）
    handleSave() {
      // 表单验证
      this.$refs.formRef.validate((valid) => {
        if (!valid) return false;

        // 验证时间范围
        if (this.isStartTimeLater) {
          this.$message.error('开始时间不能晚于结束时间');
          return;
        }

        // 验证目标受众
        const { gender, age_range, interests } = this.form.targetAudience;
        if (!gender || gender.length === 0) {
          this.$message.error('请选择性别');
          return;
        }

        if (!age_range || age_range.length !== 2 || age_range[0] >= age_range[1]) {
          this.$message.error('请设置有效的年龄范围');
          return;
        }

        if (!interests || interests.length === 0) {
          this.$message.error('请选择兴趣标签');
          return;
        }
        this.saveLoading = true;
        // 1. 确保 targetAudience 是对象（如果是字符串，先解析）
        if (typeof this.form.targetAudience === 'string') {
          this.form.targetAudience = JSON.parse(this.form.targetAudience);
        }

        // 2. 深拷贝并转换 targetAudience 为 JSON 字符串
        const formCopy = JSON.parse(JSON.stringify(this.form));
        formCopy.targetAudience = JSON.stringify(formCopy.targetAudience);
        console.log(formCopy)
        // 发送请求
        axios.post('/adCampaigns/saveOrUpdate', formCopy)
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success(this.form.campaignId ? '修改成功' : '添加成功');
                this.dialogVisible = false;
                // 刷新列表
                this.getAdList();
              } else {
                this.$message.error(response.data.message || '操作失败，请重试');
              }
            })
            .catch(() => {
              this.$message.error('网络异常，操作失败');
            })
            .finally(() => {
              this.saveLoading = false;
            });
      });
    },
    // 获取可切换的状态选项
    getStatusOptions(currentStatus) {
      return this.statusFlowMap[currentStatus] || [];
    },

    // 处理状态变更
    async handleStatusChange(row, newStatus) {
      try {

        const statusMap = {
          1: '草稿',
          2: '审核中',
          3: '运行中',
          4: '暂停',
          5: '结束'
        };

        if(row.advertisersStatus == 0){
          this.$message.error('该广告主已被禁用');
        }else {
          this.$confirm(`确定要将广告计划【${row.campaignName}】的状态更新为"${statusMap[newStatus]}"吗？此操作将${newStatus === 4 ? '同时禁用' : '不影响'}其所有广告创意`, '操作确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 调用API更新状态
            axios.post(`adCampaigns/updateStatus?campaignId=${row.campaignId}&status=${newStatus}`).then(response =>{
              if (response.data.code === 200) {
                this.$message.success('状态更新成功');
                this.getAdList();
              } else {
                this.$message.error(response.data.message || '状态更新失败');
              }
            })
          })
        }
      }catch (error) {
        this.$message.error('网络异常，状态更新失败');
      }
    },
  }
};
</script>

<style scoped>
.ad-campaigns-list {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.audience-info {
  line-height: 1.8;
}

.audience-info .label {
  color: #909399;
  margin-right: 5px;
}

.text-danger {
  color: #f56c6c;
}

.shadow-sm {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}
/* 添加下拉菜单样式 */
.el-dropdown-link {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.el-tag {
  display: inline-flex;
  align-items: center;
  cursor: pointer;
}
</style>

